package com.javaweb.dao.impl;

import com.javaweb.dao.CommentDao;
import com.javaweb.model.Comment;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Repository;
import org.springframework.util.Assert;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

/**
 * @author HLQ
 * @date 2024/10/22 16:51
 */
@Repository
@Slf4j
public class CommentDaoIml implements CommentDao {
    @Autowired
    private JdbcTemplate jdbcTemplate;

    private RowMapper<Comment> commentRowMapper =new RowMapper<Comment>() {
        @Override
        public Comment mapRow(ResultSet rs, int rowNum) throws SQLException {
            Comment comment = new Comment()
                    .setId(rs.getInt("id"))
                    .setContent(rs.getString("content"))
                    .setArticleId(rs.getInt("article_id"))
                    .setUserId(rs.getInt("user_id"))
                    .setSupport(rs.getInt("support"))
                    .setOppose(rs.getInt("oppose"))
                    .setCreateTime(rs.getTime("create_time"))
                    .setUpdateTime(rs.getTime("update_time"));
            return comment;
        }
    };

    /*
        未做：article_id不能为空；
     */
    @Override
    public int insert(Comment comment){
        Assert.notNull(comment);

        String sql = "INSERT INTO tb_comment " +
                "(content, article_id, user_id, support, oppose, create_time, update_time)" +
                " VALUES (?,?,?,?,?,?,?)";
        Object[] args = new Object[]{
                comment.getContent(),
                comment.getArticleId(),
                comment.getUserId(),
                comment.getSupport(),
                comment.getOppose(),
                comment.getCreateTime(),
                comment.getUpdateTime()
        };
        return jdbcTemplate.update(sql,args);
    }
    @Override
    public int insertSupport(Integer commentId){
        String sql = "UPDATE tb_comment SET support = support + 1 WHERE id = ?";
        return jdbcTemplate.update(sql, commentId);
    }
    @Override
    public int insertOppose(Integer commentId){
        String sql = "UPDATE tb_comment SET oppose = oppose + 1 WHERE id = ?";
        return jdbcTemplate.update(sql, commentId);
    }
    @Override
    public List<Comment> selectAllCommentsById(Integer articleId){
        String sql = "SELECT * FROM tb_comment WHERE article_id = ?";
        Object[] args = new Object[]{articleId};
        return jdbcTemplate.query(sql,args,commentRowMapper);
    }
}
